#include <stdio.h>
#include <pthread.h>

#define NUMBER 10000
//初始化互斥锁
static pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;

//把地址指向的参数值+1
void *thread_func(void *arg){
    int *q=( int *)arg;
    //加锁
    pthread_mutex_lock(&counter_mutex);
    (*q)++;
    //解锁
    pthread_mutex_unlock(&counter_mutex);
    return NULL;
}

int main(int argc, char const *argv[])
{
    int num=0;
    pthread_t thread[NUMBER];
    for(int i = 0; i < NUMBER; i++){
        //创建10000线程
        pthread_create(&thread[i], NULL, thread_func, (void *)&num);
    }
    //等待所有线程执行完毕
    for(int i = 0; i < NUMBER; i++){
        pthread_join(thread[i], NULL);
    }
    //释放锁
    pthread_mutex_destroy(&counter_mutex);
    //结果9996,并不是10000
    printf("num=%d\n", num);

    return 0;
}

